package com.yimo.chromedriver;

import com.yimo.common.util.HttpClient;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * create by jsm on 2018/9/26
 */
@Component
public class Weibo extends Crawler {
    @Value("${chromedriver.savePath:/Users/yimouser/Documents}")
    private String savePath;
    Calendar calendar = Calendar.getInstance();
    @Resource
    private HttpClient httpClient;

    public Weibo() {
        setUrl("https://www.weibo.com");
    }

    public static void main(String[] args) throws Exception {
//        climb("15168300762", "sha5362sxx", "寝室改造", 30);
    }

    ChromeDriver chromeDriver = null;

    public ChromeDriver climb(String userName, String password, String searchKey) throws Exception {


        if (chromeDriver == null) {
            chromeDriver = open();
            Thread.sleep(7000L);//停止5秒 等待网页加载
            WebElement loginnameInput = chromeDriver.findElement(By.id("loginname"));//找到用户名输入框
            loginnameInput.sendKeys(userName);//输入用户名
            WebElement passwordInput = chromeDriver.findElement(By.name("password"));//找到密码输入框
            passwordInput.sendKeys(password);//输入密码
            Thread.sleep(7000L);//停止5秒 等待网页加载
            //        chromeDriver.findElementByCssSelector("#pl_login_form  .login_btn ").click();//找到登录按钮并按下
        }
        chromeDriver.findElementByCssSelector(".gn_search_v2 .W_input").sendKeys(searchKey);//找到搜索框 输入关键词
        chromeDriver.findElementByCssSelector(".gn_search_v2 .W_ficon").click();//找到搜索按钮并按下
        while (true) {
            Thread.sleep(2500);
            try {
                List <WebElement> contents = chromeDriver.findElements(By.cssSelector(".card-feed"));

                for (int c = 0; c < contents.size(); c++) {
                    Date now = new Date();
                    calendar.setTime(now);
                    String subFolder = savePath + "/weibo/" + calendar.get(Calendar.YEAR) + "/" + (calendar.get(Calendar.MONTH) + 1) + "/" + calendar.get(Calendar.DAY_OF_MONTH) + "/" + now.getTime();
                    File subFolderFile = new File(subFolder);
                    if (subFolderFile.exists() == false) {
                        subFolderFile.mkdirs();

                    }
                    try {
                        WebElement content = contents.get(c);
                        File contentFile = new File(subFolder + "/c" + new Date().getTime() + ".txt");
                        FileOutputStream fw = new FileOutputStream(contentFile);
                        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fw, "UTF-8"));
                        bw.write(content.getText());
                        bw.flush();
                        bw.close();
                        WebElement m3 = content.findElement(By.className("m3"));
                        m3.findElement(By.tagName("img")).click();
                        Thread.sleep(500L);
                        WebElement choosepic = content.findElement(By.className("choose-pic"));
                        List <WebElement> imgs = choosepic.findElements(By.tagName("img"));
                        if (imgs != null && imgs.size() > 1) {
                            for (WebElement img : imgs) {
                                img.click();
                                String src = content.findElement(By.className("bigpic")).findElement(By.tagName("img")).getAttribute("src");
                                System.out.println(src);
                                InputStream inputStream = httpClient.doGetStream(src);
                                BufferedImage buffer = ImageIO.read(inputStream);
                                ImageIO.write(buffer, "png", new File(subFolder + "/i" + new Date().getTime() + ".png"));
                                System.out.println(src);
                            }
                        }else if(imgs!=null&&imgs.size()==1){
                            String src = content.findElement(By.className("bigpic")).findElement(By.tagName("img")).getAttribute("src");
                            System.out.println(src);
                            InputStream inputStream = httpClient.doGetStream(src);
                            BufferedImage buffer = ImageIO.read(inputStream);
                            ImageIO.write(buffer, "png", new File(subFolder + "/i" + new Date().getTime() + ".png"));
                            System.out.println(src);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        continue;
                    }

                }
                chromeDriver.findElement(By.partialLinkText("下一页")).click();
            } catch (Exception e) {
                e.printStackTrace();
                break;
            }

        }
        return chromeDriver;
    }
}